package com.citicpub_cloud.restfull.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommonUtils {

    private static final String REGEX_ID_CARD = "(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])";

    private static Logger log = LoggerFactory.getLogger(CommonUtils.class);
    public static Object copy(Object source,Object dest){
        try {
            BeanUtils.copyProperties(dest,source);
        } catch (Exception e) {
            log.error("复制属性出错");
        }
        return dest;
    }

    /**
     * 验证邮箱地址是否正确
     * @param email
     * @return
     */
    public static boolean checkEmail(String email){
        boolean flag = false;
        try{
            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     * @param mobiles
     * @return  [0-9]{5,9}
     */
    public static boolean isMobileNO(String mobiles){
        boolean flag = false;
        try{
            Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }

    public static String validCodeGen(){
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    public static List<Long> str2ListLong(String value){
        List<Long> list = new ArrayList<Long>();
        try {
            if (null!=value && value.startsWith("[") && value.endsWith("]")) {
                String vs = value.substring(1, value.length() - 1);
                if (vs.length() > 0) {
                    String[] temps = vs.split(",");
                    for (String v : temps) {
                        v = v.replace("\"","");
                        if(StringUtils.isNotBlank(v)){
                            list.add(Long.valueOf(v));
                        }
                    }
                }
            }
        }catch (Exception e){
            throw new RuntimeException("字符串转换长整型数组出错",e);
        }
        return list;
    }

    public static List<String> str2ListStr(String value){
        List<String> list = new ArrayList<String>();
        if(StringUtils.isNotBlank(value)){
            String[] vs = value.split(",");
            for(String temp:vs){
                if(StringUtils.isNotBlank(temp)){
                    list.add(temp);
                }
            }
        }
        return list;
    }

    /**
     * 是否是正确的身份证号
     * @param idCard
     * @return
     */
    public static boolean isCard(String idCard)
    {
        boolean flag = false;
        try{
            Pattern p = Pattern.compile(REGEX_ID_CARD);
            Matcher m = p.matcher(idCard);
            if(m.matches()){
                flag = true;
            }
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }
    
    public static Long length(String content) {
		Long length = Long.valueOf(0);
		if(content==null || content.length()==0){
			return length;
		}
		byte[] t1 = null;
		try {
			t1 = content.getBytes("UTF-8");
			for (int i = 0; i < t1.length;) {
				byte tt = t1[i];
				length++;
				if (CharUtils.isAscii((char) tt)) {  //1个字节的字符
					byte[] ba = new byte[1];
					ba[0] = tt;
					i++;
				}
				if ((tt & 0xE0) == 0xC0) {   //2个字节的字符
					byte[] ba = new byte[2];
					ba[0] = tt;
					ba[1] = t1[i + 1];
					i++;
					i++;
				}
				if ((tt & 0xF0) == 0xE0) {   //3个字节的字符
					byte[] ba = new byte[3];
					ba[0] = tt;
					ba[1] = t1[i + 1];
					ba[2] = t1[i + 2];
					i++;
					i++;
					i++;
				}
				if ((tt & 0xF8) == 0xF0) {   //4个字节的字符
					byte[] ba = new byte[4];
					ba[0] = tt;
					ba[1] = t1[i + 1];
					ba[2] = t1[i + 2];
					ba[3] = t1[i + 3];
					i++;
					i++;
					i++;
					i++;
				}
			}
		} catch (UnsupportedEncodingException e) {
			 log.error("计算字符长度出错",e);
		}
		return length;
	}
    
    public static int getBooleanValue(boolean val){
    	if(val){
    		return Integer.valueOf(1);
    	}else{
    		return Integer.valueOf(0);
    	}
    }
    
    
    public static void unzipEpub(byte[] fileByte ,String localPath) throws Exception {
		if (null != fileByte && fileByte.length > 0) {
			ZipInputStream zis = null;
			BufferedOutputStream bos = null;
			try {
				zis = new ZipInputStream(new ByteArrayInputStream(fileByte), Charset.forName("UTF-8"));
				ZipEntry entry = null;
				while ((entry = zis.getNextEntry()) != null) {
					String name = entry.getName();
					File target = new File(localPath , name);
					if (!target.getParentFile().exists()) {
						// 创建文件父目录
						target.getParentFile().mkdirs();
					}
					bos = new BufferedOutputStream(new FileOutputStream(target));
					int flag = 0;
					byte[] buffer = new byte[1024 * 10];
					while((flag = zis.read(buffer, 0, buffer.length)) != -1){
						bos.write(buffer, 0, flag);
					}
					bos.flush();
					bos.close();
				}
			} catch (Exception e) {
				log.error("解压epub文件出错", e);
			}finally {
				try {
					if(bos != null){
						bos.flush();
						bos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(zis != null){
					try {
						zis.closeEntry();
						zis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
    
    
    
    public static String folderPrefix(){
    	try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			Date now = new Date();
			return "zxsy_"+sdf.format(now);
		} catch (Exception e) {
			log.error("生成文件夹前缀出错", e);
		}
    	return null;
    }
    
}
